package com.example.prettyprint;

import java.util.HashSet;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class EnumerateElementsOfPolygon extends DefaultHandler {

	private boolean mInElement = false;
	private int lineCounter = 0;
	private HashSet<String> mElementNames = new HashSet<String>(5);
	private int mDepthInPolygon;
	private final String mElementQName;
	private final String mSearchInElement;
	private boolean mInSearchElement;

	public EnumerateElementsOfPolygon(String elementQName,
			String searchInElement) {
		this.mElementQName = elementQName;
		this.mSearchInElement = searchInElement;
	}

	@Override
	public void startDocument() throws SAXException {
		++lineCounter;
		this.mDepthInPolygon = 0;
	}

	public void startElement(String namespaceURI, String localName,
			String qName, Attributes attrs) throws SAXException {

		++lineCounter;

		if (qName.equalsIgnoreCase(this.mSearchInElement)) {
			this.mInSearchElement = true;
		}

		if (this.mInSearchElement) {
			if (this.mInElement) {
				if (this.mDepthInPolygon == 0)
					this.mElementNames.add(qName);

				++this.mDepthInPolygon;
			} else if (qName.equalsIgnoreCase(this.mElementQName)) {
				this.mInElement = true;
				this.mDepthInPolygon = 0;
			}
		}
	}

	public void endElement(String uri, String localName, String qName) {
		++lineCounter;

		if (qName.equalsIgnoreCase(this.mSearchInElement)) {
			this.mInSearchElement = false;
		} else if (this.mInSearchElement) {
			if (this.mInElement) {
				--this.mDepthInPolygon;

				if (qName.equalsIgnoreCase(this.mElementQName))
					this.mInElement = false;
			}
		}
	}

	public void characters(char buf[], int offset, int len) throws SAXException {
		++lineCounter;
	}

	@Override
	public void endDocument() throws SAXException {
		for (String elementInPolygonName : this.mElementNames) {
			System.out.println(elementInPolygonName);
		}
	}
}
